package com.yonyou.ypd.bill.action.add;

import com.yonyou.iuap.context.InvocationInfoProxy;
import com.yonyou.permission.util.AuthSdkFacadeUtils;
import com.yonyou.ucf.mdd.ext.bill.rule.util.BillInfoUtils;
import com.yonyou.ucf.mdd.ext.core.AppContext;
import com.yonyou.ucf.mdd.ext.dao.sql.SqlHelper;
import com.yonyou.ucf.mdd.ext.dubbo.DubboReferenceUtils;
import com.yonyou.ucf.mdd.ext.meta.MetaAttributeUtils;
import com.yonyou.ucf.mdd.ext.model.LoginUser;
import com.yonyou.ucf.mdd.ext.util.DomainUtils;
import com.yonyou.ucf.mdd.ext.util.property.ExtPropertyUtil;
import com.yonyou.ucf.transtype.model.BdTransType;
import com.yonyou.ucf.transtype.service.itf.ITransTypeService;
import com.yonyou.ypd.bill.basic.constant.BillCommonConstant;
import com.yonyou.ypd.bill.basic.entity.IBillDO;
import com.yonyou.ypd.bill.context.YpdBillContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author liangrch@yonyou.com
 * @version 1.0 单据新增处理
 * @createTime 2022/2/24 15:22
 * @description
 */
@Component
@Slf4j
public class BillAddProcessor {

    @Resource
    private ITransTypeService transTypeService;


    public void addDefaultTransType(YpdBillContext billContext, IBillDO billDO) throws Exception {
        if (billDO.getBillField().isSupportBustype()) {
            String billNum = billContext.getBaseBillContext().getcBillNo();
            if (billNum.indexOf("MobileArchive") > 0) {
                billNum = billNum.replaceAll("MobileArchive", "");
            }
            String billTypeFormId;
            if (StringUtils.isNotBlank(billContext.getBaseBillContext().getDomain())) {
                billTypeFormId = billContext.getBaseBillContext().getDomain() + "." + billNum;
            } else {
                billTypeFormId = DomainUtils.getAppName() + "." + billNum;
            }
            ITransTypeService transTypeService =  DubboReferenceUtils.getDubboService(ITransTypeService.class,billContext.getBaseBillContext().getDomain(), null);
            List<BdTransType> bdTranstypes = transTypeService.getTransTypesByFormId(InvocationInfoProxy.getTenantid(), billTypeFormId);
            if (CollectionUtils.isNotEmpty(bdTranstypes)) {
                for (BdTransType bdTranstype : bdTranstypes) {
                    if (bdTranstype.getDefault()) {
                        billDO.setAttrValue(billDO.getBillField().getField_bustype(), bdTranstype.getId());
                        billDO.setAttrValue(billDO.getBillField().getField_bustype()+"_name", bdTranstype.getName());
                    }
                }
            }

        }
    }

    public void addLastOrg(YpdBillContext billContext, IBillDO billDO) throws Exception {
        if (null == billDO) {
            return;
        }
        LoginUser user = AppContext.getCurrentUser();
        if (null == user) {// 中台事件等场景只处理了友互通token不走重登录,user判空 --yanx于2022/5/24注释
            return;
        }
        String serviceCode = billContext.getBaseBillContext().getServiceCode();
        String fullName = billContext.getBaseBillContext().getMetaFullName();
        String masterOrgField = MetaAttributeUtils.getFieldByAttributeOrName(fullName, "isMasterOrg", BillCommonConstant.KEY_DEFAULT_FIELD_ORG_ID);
        billDO.setAttrValueIfNull(BillCommonConstant.KEY_MASTERORGKEYFIELD, masterOrgField);
        if (StringUtils.isEmpty(masterOrgField)) {
            return;
        }
        if (null != billDO.getAttrValue(masterOrgField)) {
            return;
        }
        if (StringUtils.isBlank(serviceCode)){
            return;
        }
        String billNum = billContext.getBaseBillContext().getcBillNo();
        if (BillInfoUtils.isSingleOrg()) {
            billDO.setAttrValueIfNull(masterOrgField, user.getOrgId());// 简化上下文后直接使用user.getOrgId --yanx于2022/12/14注释
            return;
        }
        String defaultOrg = user.get("defaultOrg");
        if (StringUtils.isBlank(defaultOrg)) {
            Map<String,Object> params=new HashMap<>();
            params.put("billnum",billNum);
            params.put("user_id",AppContext.getUserId());
            params.put("tenant_id",AppContext.getTenantId());
            SqlSessionTemplate sqlSessionTemplate;
            if (ExtPropertyUtil.isMetaServer()) {
                sqlSessionTemplate = AppContext.getSqlSession();
            } else {
                sqlSessionTemplate = SqlHelper.use("uimeta");
            }
            List<String> list = sqlSessionTemplate.selectList("com.yonyou.ucf.mdd.ext.bill.masterorg.getLastOrg",params);
            if (CollectionUtils.isNotEmpty(list)){
                defaultOrg = list.get(0);
            }
        }
        String userHasOrgPermission = AuthSdkFacadeUtils.isUserHasOrgPermission(InvocationInfoProxy.getYhtAccessToken(), defaultOrg, serviceCode);
        billDO.setAttrValueIfNull(masterOrgField, userHasOrgPermission);
    }

}
